#delimit;
clear;
set more off;
capture log close;
set more off;
/*****
CHANGE PATH
*****/;
local out "/data";
local pathtab "/data";

use "`out'/NSC_merged.dta", clear;

/*Saving opeids from nsc to merge later to NSLDS data to figure out the state of the first school*/
preserve;

keep College_Code_Branch College_State;
rename College_Code_Branch opeid;
bys opeid: keep if _n==1;
save "`pathtab'/opeid_NSC.dta", replace;
restore;

gen Enroll_Begin_Grad_Date=Enrollment_Begin;
replace  Enroll_Begin_Grad_Date=Graduation_Date if Enrollment_Begin==.;

gen Enroll_End_Grad_Date=Enrollment_End;
replace  Enroll_End_Grad_Date=Graduation_Date if Enrollment_End==.;

sort pid Enroll_Begin_Grad_Date;

by pid: gen first_col_opeid_nsc=College_Code_Branch if _n==1;
by pid: gen first_col_enroll_nsc=Enroll_Begin_Grad_Date if _n==1;
by pid: gen first_col_state_nsc=College_State if _n==1;
gen first_col_from_grad_nsc=(first_col_enroll_nsc==Graduation_Date & Enrollment_Begin==.);
format first_col_enroll_nsc %td;


preserve;
sort pid Enroll_End_Grad_Date;
by pid: gen last_col_opeid_nsc=College_Code_Branch if _n==_N;
by pid: gen last_col_enroll_nsc=Enroll_End_Grad_Date if _n==_N;
by pid: gen last_col_state_nsc=College_State if _n==_N;
format last_col_enroll_nsc %td;

by pid: keep if _n==_N;
keep pid last_col*;
save "`pathtab'/Last_College_NSC.dta", replace;
restore;


keep pid first_col*;
keep if first_col_enroll_nsc~=.;

merge 1:1 pid using "`pathtab'/Last_College_NSC.dta";
drop _m;
gen in_nsc_alt=1;

label variable first_col_opeid_nsc "8-digit opeid for first college ever enrolled in NSC";
label variable first_col_enroll_nsc "Enrollment beginning in first college ever enrolled in NSC";
label variable first_col_state_nsc "State for first college ever enrolled in NSC";
label variable first_col_from_grad_nsc "If enrollment date comes from graduation date for first college ever enrolled in NSC";

label variable last_col_opeid_nsc "8-digit opeid for last college ever enrolled in NSC";
label variable last_col_enroll_nsc "Enrollment ends in last college ever enrolled in NSC";
label variable last_col_state_nsc "State for last college ever enrolled in NSC";

sort pid;

save "`pathtab'/First_College_NSC.dta", replace;


erase "`pathtab'/Last_College_NSC.dta";


